import { defineStore } from 'pinia'
import { listen } from '@tauri-apps/api/event'

interface AppState {
  theme: 'light' | 'dark'
}

export const useAppStore = defineStore('app', {
  state: (): AppState => ({
    theme: 'light'
  }),

  actions: {
    async initTheme() {
      // 从本地存储加载主题设置
      const savedTheme = localStorage.getItem('theme') as AppState['theme']
      if (savedTheme) {
        this.theme = savedTheme
        document.documentElement.setAttribute('data-theme', savedTheme)
      } else {
        // 如果没有保存的主题，则使用系统主题
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches
        this.theme = prefersDark ? 'dark' : 'light'
        document.documentElement.setAttribute('data-theme', this.theme)
      }

      // 监听来自系统托盘的主题切换事件
      await listen('toggle-theme', () => {
        this.toggleTheme()
      })
    },

    toggleTheme() {
      // 切换主题
      this.theme = this.theme === 'light' ? 'dark' : 'light'
      // 保存到本地存储
      localStorage.setItem('theme', this.theme)
      // 更新 HTML data-theme 属性
      document.documentElement.setAttribute('data-theme', this.theme)
    }
  }
}) 